IF OBJECT_ID(N'ssf.cmd_dir_dirname') IS NOT NULL
	DROP FUNCTION ssf.cmd_dir_dirname
GO

CREATE FUNCTION ssf.cmd_dir_dirname (
	@path NVARCHAR(2048)
)
RETURNS NVARCHAR(2048)
AS
/*
<object_header>

<object_summary>
	<purpose><![CDATA[
Return @path with its trailing \component removed.
If @path contains no \'s, output '.' (meaning the current directory).
	]]></purpose>
</object_summary>

</object_header>
*/
BEGIN
	IF NULLIF(@path, N'') IS NULL
		RETURN NULL
	IF CHARINDEX(N'\', @path) = 0
		RETURN N'.'
	
	DECLARE @htap NVARCHAR(2048) = REVERSE(@path)
		, @i SMALLINT = 1
	
	WHILE SUBSTRING(@htap, @i, 1) = N'\'
		SET @i+=1
	
	SET @i = ISNULL(NULLIF(CHARINDEX(N'\', @htap, @i), 0), @i)
	
	WHILE SUBSTRING(@htap, @i, 1) = N'\'
		SET @i+=1
	
	IF (
		SUBSTRING(@htap, @i, 2048) LIKE ':_'
		OR SUBSTRING(@htap, @i, 2048) = N''
	)
	AND SUBSTRING(@htap, @i-1, 1) = N'\'
		SET @i-=1
	
	RETURN REVERSE(SUBSTRING(@htap, @i, 2048))
END
GO
